﻿using Exam.infranstuctrue.Dto.other;
using Exam.infranstuctrue.Dto.Request.Exam;
using Exam.infranstuctrue.Dto.Request.Question;
using Exam.infranstuctrue.Dto.Respones;
using Exam.infranstuctrue.Dto.Respones.Exam;
using Exam.infranstuctrue.EFCore;
using Exam.infranstuctrue.IOC;
using Exam.infranstuctrue.Tools;
using Exam.infranstuctrue.Tools.Attributes;
using Exam.Infrastrucrure.Dto;
using Exam.Service.Interface;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exam.Service.Instance
{
    [Iinjection]
    public class QuestionService : BaseService, IQuestionServer
    {
        public readonly ExamIOC _examIOC;
        private readonly Session _session;

        public QuestionService(ExamIOC examIOC, Session session)
        {
            _examIOC = examIOC;
            _session = session;
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="orgabizationuids"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetUser(string orgabizationuids, string? token = null)
        {
            var uname = "";
            var url = "https://change.qiudaoyu.top/api/Admin/GetUser/?page=1&&limit=99999";
            var users = Http.Get(url, token);
            var user = JsonConvert.DeserializeObject<MyApiResult>(users);
            var userchilren = JsonConvert.SerializeObject(user.data);
            var result = JsonConvert.DeserializeObject<MyApiResultChliren>(userchilren);
            var res = JsonConvert.SerializeObject(result.data);
            var data = JsonConvert.DeserializeObject<List<ResponseAdminDto>>(res);

            var uids = data.Select(d => d.id).ToList();
            if (!string.IsNullOrEmpty(orgabizationuids))
            {

                var uid = orgabizationuids.Split(",");
                uname = "";
                foreach (var item2 in uid)
                {
                    var iq = data.Where(d => d.id == item2).Single();
                    uname += iq.name + ",";
                }
                uname = uname.Substring(0, uname.Length - 1);
            }
            return uname;
        }
        /// <summary>
        /// 获取试题
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <param name="IsBan"></param>
        /// <param name="IsPublish"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetQuestion(int page = 1, int limit = 10, string key = "", int IsBan = -1, int IsPublish = -1)
        {
            var question = await _examIOC._examQuestionEFCore.QueryAll(out int total, page, limit, d => d.QcreateTime, false, o => o.Qcontent.Contains(key)
            && (IsBan == -1 || o.QisBan == IsBan)
            && (IsPublish == -1 || o.QisPublish == IsPublish)).ToListAsync();

            var count = _examIOC._examQuestionEFCore.QueryAll(d => 1 == 1).Count();
            var qids = question.Select(d => d.Qid);
            var options = await _examIOC._examoptionEFCore.QueryAll(d => qids.Contains(d.Oqid)).ToListAsync();
            List<QuestionRes> questionRes = new List<QuestionRes>();
            foreach (var item in question)
            {
                List<OptionRes> optionRes = new List<OptionRes>();
                var option = options.Where(d => d.Oqid == item.Qid).ToList();
                foreach (var item2 in option)
                {
                    optionRes.Add(new OptionRes
                    {
                        Oid = item2.Oid,
                        Oqid = item2.Oqid,
                        Ocontent = item2.Ocontent,
                        OisRight = item2.OisRight,
                        OisBan = item2.OisBan,
                        Ocreatetime = item2.Ocreatetime,
                    });

                }
                questionRes.Add(new QuestionRes
                {
                    Qid = item.Qid,
                    Qanalysi = item.Qanalysi,
                    Qanswer = item.Qanswer,
                    Qauthor = item.Qauthor,
                    Qcontent = item.Qcontent,
                    Qexplain = item.Qexplain,
                    QcreateTime = item.QcreateTime,
                    Qlable = item.Qlable,
                    Qlv = item.Qlv,
                    QisBan = item.QisBan,
                    QisCheck = item.QisCheck,
                    QisPublish = item.QisPublish,
                    Qstate = item.Qstate,
                    Qtype = item.Qtype,
                    opiton = optionRes
                });
            }
            return GetResult(1, "查询成功", data: (new
            {
                total = count,
                data = questionRes,
            }));
        }
        /// <summary>
        /// 添加试题
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddQuestion(List<QuestionDto> dto)
        {
            List<ExamQuestion> examQuestion = new List<ExamQuestion>();
            List<ExamOption> examOption = new List<ExamOption>();
            foreach (var item in dto)
            {
                var qid = Config.GUID();

                examQuestion.Add(new ExamQuestion
                {
                    Qid = qid,
                    Qanalysi = item.qanalysi,
                    Qanswer = item.qanswer,
                    Qauthor = GetUser(_session.Uid, _session.GetToken()),
                    Qcontent = item.qcontent,
                    QcreateTime = DateTime.Now,
                    Qexplain = item.qexplain,
                    Qlable = item.qlable,
                    QisCheck = item.qisCheck,
                    Qlv = item.qlv,
                    Qtype = item.qtype,
                    Qstate = 1,
                    QisBan = 0,
                    QisPublish = 0,
                    Qdesc = item.qid
                });

                if (item.qisCheck < 1)
                {
                    foreach (var item2 in item.option)
                    {
                        examOption.Add(new ExamOption
                        {
                            Oid = Config.GUID(),
                            Ocontent = item2.ocontent,
                            Ocreatetime = DateTime.Now,
                            OisBan = 0,
                            OisRight = item2.oisRight,
                            Oqid = qid
                        });
                    }
                }
            }
            _examIOC._examQuestionEFCore.AddRange(examQuestion);
            await _examIOC._examQuestionEFCore.SaveChangesAsync();
            _examIOC._examoptionEFCore.AddRange(examOption);
            await _examIOC._examoptionEFCore.SaveChangesAsync();
            var result = _examIOC._examQuestionEFCore.Transactions(_examIOC._examoptionEFCore, _examIOC._examQuestionEFCore);
            if (result == true)
            {
                return GetResult(1, "添加成功");
            }
            return GetResult(0, "添加失败");
        }

        /// <summary>
        /// 删除试题
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteQuestion(List<QuestionDto> dto)
        {
            var dtoqids = dto.Select(d => d.qid).ToList();
            var question = await _examIOC._examQuestionEFCore.QueryAll(d => dtoqids.Contains(d.Qid)).ToListAsync();
            foreach (var item in question)
            {
                if (item.QisPublish == 1)
                {
                    return GetResult(0, "已发布不可删除");
                }
            }
            var option = await _examIOC._examoptionEFCore.QueryAll(d => dtoqids.Contains(d.Oqid)).ToListAsync();
            _examIOC._examQuestionEFCore.DeleteRange(question);
            _examIOC._examoptionEFCore.DeleteRange(option);
            var result = _examIOC._examQuestionEFCore.Transactions(_examIOC._examoptionEFCore, _examIOC._examQuestionEFCore);
            if (result == true)
            {
                return GetResult(1, "删除成功");
            }
            return GetResult(0, "删除失败");
        }
        /// <summary>
        /// 是否禁用
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> IsBan(List<QuestionDto> dto)
        {
            var dtoqids = dto.Select(d => d.qid).ToList();
            var questions = await _examIOC._examQuestionEFCore.QueryAll(d => dtoqids.Contains(d.Qid)).ToListAsync();
            foreach (var item in questions)
            {
                if (item.QisBan == 0)
                {
                    item.QisBan = 1;
                }
                else
                    item.QisBan = 0;
            }
            _examIOC._examQuestionEFCore.UpdateRange(questions);
            var result = _examIOC._examQuestionEFCore.SaveChanges();
            if (result > 0)
            {
                return GetResult(1, "修改成功");
            }
            else
            {
                return GetResult(0, "修改失败");
            }

        }
        /// <summary>
        /// 是否发布
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> IsPublish(List<QuestionDto> dto)
        {
            var dtoqids = dto.Select(d => d.qid).ToList();
            var question = await _examIOC._examQuestionEFCore.QueryAll(d => dtoqids.Contains(d.Qid)).ToListAsync();
            foreach (var item in question)
            {
                if (item.QisPublish == 0)
                {
                    item.QisPublish = 1;
                }
                else
                {
                    item.QisPublish = 1;
                }
            }
            _examIOC._examQuestionEFCore.UpdateRange(question);
            var result = _examIOC._examQuestionEFCore.SaveChanges();
            if (result > 0)
            {
                return GetResult(1, "修改成功");
            }
            return GetResult(0, "修改失败");
        }
        /// <summary>
        /// 获取单个试题
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateEchoQuestion(QuestionDto dto)
        {
            List<QuestionRes> questions = new List<QuestionRes>();
            var iq = await _examIOC._examQuestionEFCore.QueryAll(d => d.Qid == dto.qid).ToListAsync();
            if (iq.Any())
            {
                var options = _examIOC._examoptionEFCore.QueryAll(d => d.Oqid!.Contains(dto.qid!)).ToList();
                List<OptionRes> optionRes = new List<OptionRes>();
                foreach (var item in options)
                {
                    optionRes.Add(new OptionRes()
                    {
                        Oid = item.Oid,
                        Oqid = item.Oqid,
                        Ocontent = item.Ocontent,
                        OisRight = item.OisRight,
                        Ocreatetime = item.Ocreatetime,
                        OisBan = item.OisBan,
                    });
                }
                var question = iq.Single();
                questions.Add(new QuestionRes()
                {
                    Qid = question.Qid,
                    QisCheck = question.QisCheck,
                    Qauthor = question.Qauthor,
                    Qlv = question.Qlv,
                    Qstate = question.Qstate,
                    Qcontent = question.Qcontent,
                    Qexplain = question.Qexplain,
                    Qlable = question.Qlable,
                    Qtype = question.Qtype,
                    Qanalysi = question.Qanalysi,
                    QcreateTime = question.QcreateTime,
                    opiton = optionRes
                });
                return GetResult(1, "查询成功", questions);
            }
            return GetResult(0, "查无此数据");
        }

    }
}
